/**
 * @author 徐梦轲
 * @data 2022/5/25 0025 - 23:27
 */

/**
 *
 * @author     ：徐梦轲
 * @date       ：2022/5/25 0025 23:27
 */
class ListNode {
       int val;
       ListNode next;
       ListNode(int x) {
           val = x;
           next = null;
       }
}
public class Solution {
    //解法1：快慢指针
    public ListNode detectCycle(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
                break;
            }
        }
        if (fast == null || fast.next == null) {
            return null;
        }
        slow = head;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }

    //解法2：哈希表法
}
